 import { SettingsService, MenuService, User, TitleService, ALAIN_I18N_TOKEN } from '@delon/theme';
import { Component, OnDestroy, Inject, Optional, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';
import { NzMessageService, NzModalService } from 'ng-zorro-antd';
import { SocialService, SocialOpenType, TokenService, DA_SERVICE_TOKEN } from '@delon/auth';
import { ReuseTabService } from '@delon/abc';
import { environment } from '@env/environment';
import { _HttpClient } from '@delon/theme';
import { Constant, ServiceResult } from '@core/constant';
import { catchError } from 'rxjs/operators/catchError';
import { of } from 'rxjs/observable/of';
import { LoginService } from '../../../service/login.service';
import { UserService } from '../../../service/user/user.service';
import { zip } from 'rxjs';
import { HttpClient } from '@angular/common/http';
import { I18NService } from '@core/i18n/i18n.service';
import { TranslateService } from '@ngx-translate/core';

@Component({
    selector: 'passport-login',
    templateUrl: './login.component.html',
    styleUrls: [ './login.component.less' ],
    providers: [ SocialService ]
})
export class UserLoginComponent implements OnInit {

    form: FormGroup;
    error = '';
    loading = false;

    ngOnInit() {
        // 只要进入登录页, 默认清空用户信息
        this.tokenService.set(null);
        this.title.setTitle("Login In")
    }
    constructor(
        private translate: TranslateService,
        @Inject(ALAIN_I18N_TOKEN) private i18n: I18NService,
        private httpClient: HttpClient,
        fb: FormBuilder,
        private router: Router,
        public msg: NzMessageService,
        private userSrc: UserService,
        private modalSrv: NzModalService,
        private settingsService: SettingsService,
        private login: LoginService,
        private cnt: Constant,
        private menuService: MenuService,
        private title: TitleService,
        @Optional() @Inject(ReuseTabService) private reuseTabService: ReuseTabService,
        @Inject(DA_SERVICE_TOKEN) private tokenService: TokenService) {
            this.form = fb.group({
                userName: [null, [Validators.required]],
                password: [null, Validators.required],
                remember: [false]
            });
            modalSrv.closeAll();
    }

    // region: fields

    get userName() { return this.form.controls.userName; }
    get password() { return this.form.controls.password; }

    // endregion



    submit() {
        this.error = '';
        let homeUrl='';
        this.userName.markAsDirty();
        this.userName.updateValueAndValidity();
        this.password.markAsDirty();
        this.password.updateValueAndValidity();
        if (this.userName.invalid || this.password.invalid) {
            return;
        }
        this.loading = true;
        this.login.login(this.userName.value, this.password.value).pipe(
            catchError(err => {
              console.log("########"+err);

              return of(err);
            })
        ).subscribe(data=>{
            // 清空路由复用信息

          let flagl = data.status;

          this.reuseTabService.clear();
          if (flagl=='undefined'||flagl!=500) {
                // 设置token
                this.tokenService.set({token: data});
            console.log("this.userName.value**********"+this.userName.value);

            // 获取用户信息
                this.login.info(this.userName.value).subscribe(data => {
                    // 设置用户信息
                  homeUrl = data.data.homeUrl;
                  console.log("data.data.currentDepart.orgCode,"+JSON.stringify(data));
                  this.settingsService.setUser({

                        name: data.data.realName,
                        username: data.data.userName,
                        id: data.data.id,
                        sysorgCode:data.data.currentDepart.orgCode,
                        email: '',
                        avatar: `${data.image ? `${this.cnt.baseUrl}/api/file/avatar/` + data.image : "./assets/tmp/img/avatar.png"}`,
                        elements: ''
                    });


                }, error => {
                    this.loading = false;
                    this.tokenService.set({token: ''});
                    this.error = error['message'];
                });


                // 加载国际化文件
                new Promise((resolve, reject) => {
                    zip(
                        this.httpClient.get(`assets/tmp/i18n/${this.i18n.defaultLang}.json`)
                    ).pipe(
                        // 接收其他拦截器后产生的异常消息
                        catchError((err) => {
                            resolve(null);
                            return [];
                        })
                    ).subscribe(([langData]) => {

                        // setting language data
                        this.translate.setTranslation(this.i18n.defaultLang, langData);
                        this.translate.setDefaultLang(this.i18n.defaultLang);

                        // 获取菜单信息
                        this.login.menu(this.userName.value).subscribe(data => {
                        //     // 初始化菜单
                          console.log("this.login.menu(this.userName.value)"+this.userName.value);
                          this.menuService.clear();
                          if(!(data.data===null||data.data==="")){
                            console.log("this.menuService.add(data.data as any)"+JSON.stringify(data.data));

                            this.menuService.add(data.data as any);
                            sessionStorage.removeItem(this.cnt.lockFlag);
                            this.router.navigate([homeUrl]);
                          }else{
                            this.tokenService.set({token: ''});
                            this.error = '菜单获取失败';
                          }
                        }, error => {
                            this.tokenService.set({token: ''});
                            this.error = '菜单获取失败';
                        });
                    })
                });
            } else {
                this.loading = false;
                this.error = data.message || '账号或密码错误'
            }
        }, error => { this.error = error['message'] || '系统故障'; this.loading = false } );
    }
}
